using AutoMapper;
using B.S.BaseData.Api.Write.Application.Command.Procurements;
using B.S.BaseData.Domain;
using MediatR;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace B.S.BaseData.Api.Write.Application.CommandHandler.Procurements
{
    /// <summary>
    /// 更新采购命令处理器
    /// </summary>
    public class UpdateProcurementCommandHandler : IRequestHandler<UpdateProcurementCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Procurement> procurement;
        private readonly IMapper map;

        public UpdateProcurementCommandHandler(IBaseRepository<Procurement> procurement, IMapper map)
        {
            this.procurement = procurement;
            this.map = map;
        }

        public async Task<ApiResult<int>> Handle(UpdateProcurementCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            try
            {
                // 获取要更新的采购记录
                var existingProcurement = await procurement.GetByIdAsync(request.ProcurementId);
                
                if (existingProcurement == null || existingProcurement.IsDeleted)
                {
                    res.Message = "采购记录不存在或已删除";
                    res.Code = ApiEnum.更新失败;
                    return res;
                }

                // 使用AutoMapper将请求映射到现有实体
                map.Map(request, existingProcurement);

                // 执行更新操作
                int r = await procurement.UpdateAsync(existingProcurement);

                if (r > 0)
                {
                    res.Message = "更新成功";
                    res.Code = ApiEnum.更新成功;
                    res.data = r;
                }
                else
                {
                    res.Message = "更新失败";
                    res.Code = ApiEnum.更新失败;
                }
            }
            catch (Exception ex)
            {
                res.Message = "更新失败: " + ex.Message;
                res.Code = ApiEnum.更新失败;
            }

            return res;
        }
    }
}

